package org.bite.utils;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo04_Insert {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null; //增删改不返回结果集 只有受影响的行数

        try {
            //1.获取数据库连接
            connection=DBUtil.getConnection();//不用new操作

            //定义SQL
            String sql="select * from student where name=?";

            //3.定义SQL预处理对象,存入SQL语句
            statement= connection.prepareStatement(sql);

            //4.接收用户输入
            System.out.println("请输入姓名:");
            Scanner sc=new Scanner(System.in);
            String inName=sc.next();

            //5.真实数据替换占位符
            statement.setString(1,inName);

            //6.执行sql获取结果
            resultSet= statement.executeQuery();

            while(resultSet.next()){//初始游标为第一行前,next()到下一行
                //获取具体列的值 用相应的数据类型接收(或者创建对象接收)
                //resultSet.getLong(1); 通过列名或者顺序获取
                long id=resultSet.getLong("id");
                String name=resultSet.getString("name");
                String sno=resultSet.getString("sno");
                int age=resultSet.getInt("age");
                System.out.println(MessageFormat.format("学生编号={0},学号={1},姓名={2},年龄={3}",id,sno,name,age));
                //格式化输出字符串 数字为占位符
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(resultSet,statement,connection);
        }
    }
}
